<template>
  <view class="container">
    <div
      v-for="(group, index) in dataList"
      :key="index"
    >
      <div class="date-box">
        {{ group[0].date }}
      </div>
      <span
        v-for="(item, itemIndex) in group"
        :key="itemIndex"
      >
        <img
          :src="item.src"
          alt="Image"
          class="image"
          @click="getImgInfo(item.name)"
        >
      </span>
    </div>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const dataList = ref([])

onMounted(() => {
  load()
})

const load = () => {
  const formData = new FormData()
  formData.append('userId', window.localStorage.getItem("userId"))
  axios.post('http://localhost:8086/Img/history',
    { userId: formData.get('userId') },
    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
    .then(function (response) {
      const groupedData = groupByDate(response.data.data)
      dataList.value = groupedData
      // console.log(dataList.value)
    })
    .catch(function (error) {
      console.log(error)
    })
}

const groupByDate = (data) => {
  const groups = {}
  data.forEach(item => {
    const date = new Date(item.time).toLocaleDateString()
    if (!groups[date]) {
      groups[date] = []
    }
    groups[date].push({
      date,
      src: `data:image/png;base64,${item.data}`,
      name: item.name,
      id: item.id
    })
  })
  return Object.values(groups)
}

const getImgInfo = (name) => {
  // console.log('Image Name:', name)
  uni.navigateTo({
    url: '/pages/search-prod-show/search-prod-show?prodName=' + name
  })
}
</script>

<style scoped lang="scss">
@use './photoHistory-page.scss';
</style>
